const BaseIpcHandler = require('../BaseIpcHandler');
const fs = require('fs');

class DeleteLocalModelHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> DeleteLocalModelHandler params = ', params);
        const { local_model_id } = params;

        // 业务逻辑
        let result = null;
        try {
            // 删除对应记录的所有训练目录
            let records = await this.app.db.train_records.getRecords(local_model_id);
            for (let i = 0; i < records.length; i++) {
                let record = records[i];
                let output_dir = record.output_dir;
                if (fs.existsSync(output_dir)) {
                    fs.rmSync(output_dir, { recursive: true });
                }
            }

            // 删除对应的数据库记录
            await this.app.db.train_records.deleteRecords(local_model_id);
            await this.app.db.models_local.delete(local_model_id);
            result = { code: 0, msg: 'Delete Local Model OK!' };
        } catch (err) {
            console.error(`Error delete local model: `, err);
            result = { code: -1, msg: err.message };
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = DeleteLocalModelHandler;
